package com.yyz.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.yyz.common.BaseContext;
import com.yyz.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 检查用户是否已经完成登录
 * @author yyz
 * @create 2023-07-18 21:08
 */
@Slf4j
//@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    //目标资源方法执行前执行，返回true：放行；返回false：不放行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求url
        String url = request.getRequestURL().toString();

        log.info("拦截到请求：{}",url);

        if (request.getSession().getAttribute("employee") != null) {
            Long id = (Long) request.getSession().getAttribute("employee");
            BaseContext.setThreadLocal(id);

            return true;
        }

        response.getWriter().write(JSONObject.toJSONString(R.error("NOTLOGIN")));
        return false;

    }
}
